package com.netdisk.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.netdisk.dao.Dao;
import com.netdisk.entity.User;

/**
 * 用户类, 分为单用户,和公司级用户
 * 
 * @author chenlong 2013-4-13
 */
@Repository(value = "userDao")
public class UserDao extends Dao<User> {

	@Override
	public void save(User obj) {
		Session session = sessionFactory.getCurrentSession();
		session.save(obj);
	}

	@Override
	public void update(User obj) {
		Session session = sessionFactory.getCurrentSession();
		session.update(obj);
	}

	@Override
	public void delete(User obj) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(obj);

	}

	@Override
	public List<User> findAll() {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		users = session.createQuery("from User").list();
		return users;
	}

	@Override
	public User findById(String id) {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		User user = null;
		Query  query = session.createQuery("from User where id=:id");
		query.setString("id", id);
		users = query.list();
		if (!users.isEmpty()) {
			user = users.get(0);
		}
		return user;
	}

	@Override
	public List<User> findByTop(int from, int max) {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		Query query = session.createQuery("from User");
		query.setFirstResult(from);
		query.setMaxResults(max);
		users = query.list();
		return users;
	}

	/**
	 * 
	 * @param group
	 *            传入还没有持久化的dto, loginName判断是否用户名已经被 使用了.
	 * @return true or false
	 */
	public boolean existWithLoginName(String loginName) {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		Query query = session
				.createQuery("from User where loginName=:loginName");
		query.setString("loginName", loginName);
		users = query.list();
		// transaction.commit();
		if (users.isEmpty()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 通过loginName ,返回用户, 用于登录验证.
	 * 
	 * @param loginName
	 * @return user
	 */
	public User findByLoginName(String loginName) {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		User user = null;
		Query query = session
				.createQuery("from User where loginName=:loginName");
		query.setString("loginName", loginName);
		users = query.list();

		if (!users.isEmpty()) {
			user = users.get(0);
		}
		return user;
	}
	
	public List<User> findByCompanyId(String companyId) {
		Session session = sessionFactory.getCurrentSession();
		List<User> users = null;
		Query query = session
				.createQuery("from User where companyId=:companyId");
		query.setString("companyId", companyId);
		users = query.list();
		return users;
	}

}
